//
//  RBTimer.m
//  RBDemoProj
//
//  Created by Lan on 2019/1/2.
//  Copyright © 2019年 SummerTea. All rights reserved.
//

#import "RBTimer.h"
#import "RBProxy.h"

@interface RBTimer()

@property(nonatomic, assign) double interval;
@property(nonatomic, assign) NSInteger maxCount;
@property(nonatomic, copy) void(^block)(float countF, NSInteger dountI);

@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic, assign) double passTime;

@end

@implementation RBTimer

#pragma mark - System

- (void)dealloc
{
    [self stop];
    NSLog(@"timer dealloc");
}

#pragma mark - Public

- (void)startTimerWithInterval: (double)interval
                         block: (void(^)(float countF, NSInteger countI))block
{
    [self stop];
    self.passTime = 0;
    self.maxCount = 0;
    self.interval = interval;
    self.block = block;
    self.timer = self.timer;
    block(0, 0);
}

- (void)startTimerWithMaxCount: (NSInteger)maxCount
                      interval: (double)interval
                         block: (void(^)(float countF, NSInteger dountI))block
{
    [self stop];
    self.passTime = 0;
    self.maxCount = maxCount;
    self.interval = interval;
    self.block = block;
    self.timer = self.timer;
    block(maxCount, maxCount);
}

- (void)pause
{
    _timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:MAXFLOAT];
}

- (void)restart
{
    if ([_timer.fireDate timeIntervalSinceNow] > 3600*24*365)
    {
        _timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:self.interval];
    }
}

- (void)stop
{
    if (_timer)
    {
        [_timer invalidate];
        _timer = nil;
    }
}

#pragma mark - Event

- (void)timerEvent
{
    double countF;
    NSInteger countI;
    self.passTime += self.interval;
    if (self.maxCount > 0)
    {
        countF = self.maxCount - self.passTime;
        if (countF <= 0)
        {
            countF = 0;
            [self stop];
        }
        countI = (NSInteger)ceilf(countF);
    }
    else
    {
        countF = self.passTime;
        countI = (NSInteger)countF;
    }
    if (self.block)
    {
        self.block(countF, countI);
    }
}

#pragma mark - Getter

- (NSTimer *)timer
{
    if (!_timer)
    {
        self.timer = ({
            NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:self.interval target:[RBProxy proxyWithTarget:self] selector:@selector(timerEvent) userInfo:nil repeats:YES];
            timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:self.interval];
            [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
            timer;
        });
    }
    return _timer;
}

@end
